// pages/address/address.js
var CityData = require('../../../utils/city.js')
var api = require('../../../api/api.js')
//获取应用实例
var app = getApp()
Page({
  data: {
    provinces: [],
    citys: [],
    districts: [],
    selProvince: '请选择',
    selCity: '请选择',
    selDistrict: '请选择',
    selAreaId: "",
    selProvinceIndex: 0,
    selCityIndex: 0,
    selDistrictIndex: 0,
  },

  onLoad: function(options) {
    let that = this;
    this.initCityData(1);
    var index = options.index;
    if (index != null) {
      // 初始化原数据
      wx.showLoading();
      wx.request({
        url: api.AddressGet,
        data: {

        },
        method: "POST",
        header: {
          'Content-Type': 'application/json',
          'X-bocang-Authorization': wx.getStorageSync('token')
        },
        success: function (res) {
          wx.hideLoading();
          if (res.data.error_code == 0) {
            var consignees = res.data.consignees[index];
            that.setData({
              id: consignees.id,
              addressData: consignees,
              selProvince: consignees.regions[1].name,
              selCity: consignees.regions[2].name,
              selDistrict: consignees.regions[3].name,
              selAreaId: consignees.regions[3].id
            });
            that.setDBSaveAddressId(res.data.consignees);
            return;
          } else {
            wx.showModal({
              title: '提示',
              content: '无法获取收货地址数据',
              showCancel: false
            })
          }
        }
      })
    }
    
  },

  initCityData: function (level, obj) {
    if (level == 1) {
      var pinkArray = [];
      for (var i = 0; i < CityData.cityData.length; i++) {
        pinkArray.push(CityData.cityData[i].name);
      }
      this.setData({
        provinces: pinkArray
      });
    } else if (level == 2) {
      var pinkArray = [];
      var dataArray = obj.cityList
      for (var i = 0; i < dataArray.length; i++) {
        pinkArray.push(dataArray[i].name);
      }
      this.setData({
        citys: pinkArray
      });
    } else if (level == 3) {
      var pinkArray = [];
      var dataArray = obj.districtList
      for (var i = 0; i < dataArray.length; i++) {
        pinkArray.push(dataArray[i].name);
      }
      this.setData({
        districts: pinkArray
      });
    }

  },
  bindPickerProvinceChange: function (event) {
    var selIterm = CityData.cityData[event.detail.value];
    this.setData({
      selProvince: selIterm.name,
      selProvinceIndex: event.detail.value,
      selCity: '请选择',
      selCityIndex: 0,
      selDistrict: '请选择',
      selAreaId: "",
      selDistrictIndex: 0
    })
    this.initCityData(2, selIterm)
  },

  bindPickerCityChange: function (event) {
    var selIterm = CityData.cityData[this.data.selProvinceIndex].cityList[event.detail.value];
    this.setData({
      selCity: selIterm.name,
      selCityIndex: event.detail.value,
      selDistrict: '请选择',
      selAreaId: "",
      selDistrictIndex: 0
    })
    this.initCityData(3, selIterm)
  },

  bindPickerChange: function (event) {
    var selIterm = CityData.cityData[this.data.selProvinceIndex].cityList[this.data.selCityIndex].districtList[event.detail.value];
    if (selIterm && selIterm.name && event.detail.value) {
      this.setData({
        selDistrict: selIterm.name,
        selAreaId: selIterm.areaId,
        selDistrictIndex: event.detail.value
      })
    }
  },

  //取消按钮
  bindCancel: function () {
    wx.navigateBack({})
  },

  //保存地址
  bindSave: function (e) {
    var that = this;
    var consignee = that.data.id;
    var linkMan = e.detail.value.linkMan;
    var address = e.detail.value.address;
    var mobile = e.detail.value.mobile;
    var code = e.detail.value.code;

    if (linkMan == "") {
      wx.showModal({
        title: '提示',
        content: '请填写联系人姓名',
        showCancel: false
      })
      return
    }
    if (mobile == "") {
      wx.showModal({
        title: '提示',
        content: '请填写手机号码',
        showCancel: false
      })
      return
    }
    if (this.data.selProvince == "请选择") {
      wx.showModal({
        title: '提示',
        content: '请选择地区',
        showCancel: false
      })
      return
    }
    if (this.data.selCity == "请选择") {
      wx.showModal({
        title: '提示',
        content: '请选择地区',
        showCancel: false
      })
      return
    }
    var cityId = CityData.cityData[this.data.selProvinceIndex].cityList[this.data.selCityIndex].id;
    var districtId;
    if (this.data.selDistrict == "请选择" || !this.data.selDistrict) {
      districtId = '';
    } else {
      districtId = CityData.cityData[this.data.selProvinceIndex].cityList[this.data.selCityIndex].districtList[this.data.selDistrictIndex].id;
    }
    if (address == "") {
      wx.showModal({
        title: '提示',
        content: '请填写详细地址',
        showCancel: false
      })
      return
    }
    // if (code == "") {
    //   wx.showModal({
    //     title: '提示',
    //     content: '请填写邮编',
    //     showCancel: false
    //   })
    //   return
    // }
    var region = this.data.selAreaId;
    if (!consignee) {
      that.addAddress(linkMan, mobile, "", "", region, address, "")
    } else {
      that.updateAddress(consignee, linkMan, mobile, "", "", region, address, "")
    }
  },

  addAddress: function (linkMan, mobile, tel, zip_code, region, address, identity) {
    wx.request({
      url: api.AddressAdd,
      data: {
        name: linkMan,
        mobile: mobile,
        tel: "",
        zip_code: "",
        region: region,
        address: address,
        identity: ""
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.error_code == 0) {
          wx.showToast({
            title: '保存成功',
            icon: "success",
            image: "/images/success.png"
          });
        }
        // 跳转到结算页面
        wx.navigateBack({})
      }
    })
  },

  updateAddress: function (consignee, linkMan, mobile, tel, zip_code, region, address, identity) {
    wx.request({
      url: api.AddressUpdate,
      data: {
        consignee: consignee,
        name: linkMan,
        mobile: mobile,
        tel: "",
        zip_code: "",
        region: region,
        address: address,
        identity: ""
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.error_code == 0) {
          wx.showToast({
            title: '保存成功',
            icon: "success",
            duration: 500,
            image: "/images/success.png"
          });
        }
        // 跳转到结算页面
        wx.navigateBack({})
      }
    })
  },

  setDBSaveAddressId: function(data) {
    var retSelIdx = 0;
    for (var i = 0; i < CityData.cityData.length; i++) {
      if (data.provinceId == CityData.cityData[i].id) {
        this.data.selProvinceIndex = i;
        for (var j = 0; j < CityData.cityData[i].cityList.length; j++) {
          if (data.cityId == CityData.cityData[i].cityList[j].id) {
            this.data.selCityIndex = j;
            for (var k = 0; k < CityData.cityData[i].cityList[j].districtList.length; k++) {
              if (data.districtId == CityData.cityData[i].cityList[j].districtList[k].id) {
                this.data.selDistrictIndex = k;
              }
            }
          }
        }
      }
    }
  },

  selectCity: function() {

  },

  //删除地址
  deleteAddress: function(e) {
    var that = this;
    var consignee = that.data.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该收货地址吗？',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: api.AddressDelete,
            data: {
              consignee: consignee
            },
            method: "POST",
            header: {
              'Content-Type': 'application/json',
              'X-bocang-Authorization': wx.getStorageSync('token')
            },
            success: (res) => {
              wx.navigateBack({})
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  defaultAddress: function () {
    let that = this;
    var consignee = that.data.id;
    wx.request({
      url: api.AddressSetDefault,
      data: {
        consignee: consignee
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.navigateBack({})
      }
    })
  },

  //从微信读取
  readFromWx: function() {
    let that = this;
    wx.chooseAddress({
      success: function(res) {
        let provinceName = res.provinceName;
        let cityName = res.cityName;
        let diatrictName = res.countyName;
        let retSelIdx = 0;

        for (var i = 0; i < CityData.cityData.length; i++) {
          if (provinceName == CityData.cityData[i].name) {
            let eventJ = {
              detail: {
                value: i
              }
            };
            that.bindPickerProvinceChange(eventJ);
            that.data.selProvinceIndex = i;
            for (var j = 0; j < CityData.cityData[i].cityList.length; j++) {
              if (cityName == CityData.cityData[i].cityList[j].name) {
                //that.data.selCityIndex = j;
                eventJ = {
                  detail: {
                    value: j
                  }
                };
                that.bindPickerCityChange(eventJ);
                for (var k = 0; k < CityData.cityData[i].cityList[j].districtList.length; k++) {
                  if (diatrictName == CityData.cityData[i].cityList[j].districtList[k].name) {
                    //that.data.selDistrictIndex = k;
                    eventJ = {
                      detail: {
                        value: k
                      }
                    };
                    that.bindPickerChange(eventJ);
                  }
                }
              }
            }

          }
        }

        that.setData({
          wxaddress: res,
        });
      }
    })
  }
})